package com.manager.enterprise.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.manager.commons.utils.StringUtil;
import com.manager.core.shiro.config.ShiroUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录状态拦截
 */
public class CustomInterceptor implements HandlerInterceptor {

    /**
     * 预处理
     * 处理器方法调用之前执行。
     * 只有该方法有返回值，返回值是布尔类型，true表示放行，false表示拦截。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获得请求路径的uri
        String uri = request.getRequestURI();
        if (uri.endsWith("/login")) {
            return true;
        } else {
            if (!ShiroUtil.isAuthenticated() || StringUtil.isEmpty(ShiroUtil.currentAccount())) {
                response.setHeader("interceptorInfo", "ajax_sessiontimeout");
                return false;
            }
        }

        return true;

    }

    /**
     * 处理器方法调用之后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // 获得请求路径的uri
    }

    /**
     * 渲染完成后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求处理完毕后的清理工作，例如释放资源等
    }

    /**
     * 判断是不是ajax请求
     *
     * @param request
     * @return
     */
    protected boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header);
    }
}